
package com.trydofor.id.exec;

import java.util.Map;

import com.trydofor.aloe.exception.Exceptions;
import com.trydofor.id.byta.Bytable;
import com.trydofor.id.doer.shell.ArgChecker;
import com.trydofor.id.doer.shell.Command;
import com.trydofor.id.doer.shell.Executer;
import com.trydofor.id.doer.shell.Outcome;
import com.trydofor.id.mina.PacketDecoder;
import com.trydofor.id.ware.WareFactory;

/**
 * @author : Shi Rongjiu (www.trydofor.com)
 */
public class DecoderExe implements Executer {
    
    private final Command       registerDecoder;
    
    private final PacketDecoder decoder;
    private final WareFactory   factory;
    
    /**
     * constructor
     * 
     * @param doer the shell
     * @param factory the ware context
     * @throws NullPointerException if doer or factory is null
     */
    public DecoderExe(PacketDecoder doer, WareFactory factory) {
        Exceptions.checkNullPointer(doer);
        Exceptions.checkNullPointer(factory);
        this.decoder = doer;
        this.factory = factory;
        this.registerDecoder = DecoderCmd.registerDecoder();
    }
    
    /**
     * {@inheritDoc}
     */
    public Outcome execute(Command command, Map<String, String> argdata) {
        
        String err = ArgChecker.check(command, argdata);
        if (err != null) return new Outcome(-1, null, err);
        
        if (registerDecoder.getAlias().equals(command.getAlias())) {
            return registerCommand(command, argdata);
        }
        
        return new Outcome(-1, null, "Command is unsupported:" + command);
    }
    
    // ------------------
    private Outcome registerCommand(Command command, Map<String, String> argdata) {
        try {
            String nmn = argdata.get("name");
            Bytable<?> bd = (Bytable<?>) factory.getInstance(nmn);
            decoder.register(bd);
            return new Outcome(0, "register the decoder", null);
        }
        catch (Exception e) {
            return new Outcome(-1, null, Exceptions.printStackTrace(e));
        }
        
    }
}
